import React, { ReactNode, Component } from 'react';
import { Form, Select, DatePicker, Input, Button, Table, Icon } from 'antd';
import { connect } from 'dva';
import { withRouter } from 'react-router-dom';
import moment from 'moment';
import _ from 'lodash';

import { checkPermission } from '@/utils/resolvePermission';
import { getTransationColumns, formatObj, checkHasChanged } from '../until';
import { ORDER_TYPE_DETAIL, PAGINATION_OPTION } from '../data';
import { getTransactionList, exportTransactionList } from '../service';
import { handleSendData } from '@/utils/tools';
import exportExcel from '@/utils/export';

const FormItem = Form.Item;
const { RangePicker } = DatePicker;
const { Option } = Select;

interface StateType {
  [propName: string]: any;
}

// 初始化表单筛选项
function initTableFilters(): object {
  return {
    parentName: undefined, // 所属代理
    status: '-1', // 状态
    userType: '-1', // 账户类型
  };
}

// 初始化时间
function initialTimeWithMill() {
  const lastMoment = moment().subtract(2, 'days');
  lastMoment.set({ hour: 0, minute: 0, second: 0 });
  return [lastMoment, moment('23:59:59', 'HH:mm:ss')];
}

class Transaction extends Component<StateType> {
  public state: StateType = {
    subMenu: [],
    tableData: {
      list: [],
      total: 0,
    },
    tableFilters: initTableFilters(),
    page: 1,
    size: 10,
    loading: false,
  };

  public exportPermission = 'new-finance-report-abnormal-export';

  componentDidMount() {
    this.getTableData();
  }

  private getColumnSearchProps = dataIndex => ({
    filterDropdown: ({ confirm }: { confirm: any }) => (
      <div style={{ padding: '8px' }}>
        <Input
          ref={node => {
            this.searchInput = node;
          }}
          value={this.state.tableFilters[dataIndex]}
          onChange={e => {
            const state = _.cloneDeep(this.state);
            state.tableFilters[dataIndex] = e.target.value;
            this.setState({
              ...state,
            });
          }}
          onPressEnter={() => this.getTableData(confirm)}
          style={{ width: 188, marginBottom: 8, display: 'block' }}
          allowClear
        />
        {/* 搜索 */}
        <Button
          type="primary"
          onClick={() => {
            const { payload } = this.state;
            this.setState({ payload: { ...payload, page: 1 } }, () => this.getTableData(confirm));
          }}
          icon="search"
          size="small"
          style={{ width: 90, marginRight: 8 }}
        >
          搜索
        </Button>
      </div>
    ),
    filterIcon: filtered => (
      <Icon type="search" style={{ color: filtered ? '#1890ff' : undefined }} />
    ),
  });

  private getParams = (data?: object) => {
    let orderTypeValue = '';
    let params = this.props.form.getFieldsValue();
    const { tableFilters, page, size } = this.state;
    if (data) params = data;
    const { orderType } = params;
    orderTypeValue = orderType.length > 0 ? orderType.join(',') : orderTypeValue;
    return handleSendData({ ...params, ...tableFilters, page, size, orderType: orderTypeValue });
  };

  private getTableData = (confirm?: any) => {
    if (confirm) confirm();
    this.props.form.validateFieldsAndScroll((err: any, values: any) => {
      if (!err) {
        const params = this.getParams(values);
        this.setState({ loading: true });
        getTransactionList(params).then((res: any) => {
          if (res) {
            const { code, data } = res;
            if (code === 1 && data) {
              this.setState({ tableData: data, loading: false });
            }
          }
        });
      }
    });
  };

  private handleExport = () => {
    const params = this.getParams();
    exportTransactionList(params).then((res: any) => {
      if (res) {
        const { code, data } = res;
        if (code === 1 && data) {
          const formatKeys = Object.keys(formatObj);
          data.list.forEach((item: any) => {
            _.forEach(formatKeys, f => {
              item[f] = formatObj[f](item[f], item);
            });
          });
          exportExcel(getTransationColumns(), data.list, '交易明细报表.xlsx');
        }
      }
    });
  };

  private onTableChange = (pagination: any, filters: any, sort?: any) => {
    const { current, pageSize } = pagination;
    const { tableFilters } = this.state;
    const tableFiltersData = { ...tableFilters };
    if (filters) {
      Object.keys(filters).forEach((item: string) => {
        tableFiltersData[item] = filters[item]['0'];
      });
    }
    const hasChanged = filters ? checkHasChanged(tableFilters, filters) : false;
    this.setState(
      { tableFilters: tableFiltersData, page: hasChanged ? 1 : current, size: pageSize },
      () => {
        this.getTableData();
      },
    );
  };

  private handleSubmit = (e: any) => {
    e.preventDefault();
    this.getTableData();
  };

  private handleReset = () => {
    this.props.form.resetFields();
    this.setState(
      {
        page: 1,
        tableFilters: initTableFilters(),
      },
      () => {
        this.getTableData();
      },
    );
  };

  // 渲染表单
  private renderFilters = (): ReactNode => {
    const { getFieldDecorator } = this.props.form;
    const { subMenu } = this.state;
    const orderTypeInitialValue = ORDER_TYPE_DETAIL.map((item: any) => item.value);

    return (
      <Form layout="inline" onSubmit={this.handleSubmit}>
        <FormItem>
          {getFieldDecorator('timeRangeType', {
            initialValue: 1,
          })(
            <Select style={{ width: 120 }}>
              {/* 操作时间 */}
              <Option value={1}>操作时间</Option>
              {/* 帐变时间 */}
              <Option value={2}>帐变时间</Option>
            </Select>,
          )}
        </FormItem>

        <FormItem>
          {getFieldDecorator('time', {
            initialValue: initialTimeWithMill(),
          })(
            <RangePicker
              format="YYYY-MM-DD HH:mm:ss"
              placeholder={['开始时间', '结束时间']}
              showTime={{
                hideDisabledOptions: true,
                defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')],
              }}
            />,
          )}
        </FormItem>

        {/* 交易订单号 */}
        <FormItem label="交易订单号">
          {getFieldDecorator('orderId', {
            initialValue: '',
          })(<Input placeholder="请输入交易订单号" />)}
        </FormItem>

        {/* 账户名 */}
        <FormItem label="账户名">
          {getFieldDecorator('username', {
            initialValue: '',
          })(<Input placeholder="请输入账户名" />)}
        </FormItem>

        {/* 交易类型 */}
        <FormItem label="交易类型">
          {getFieldDecorator('orderType', {
            initialValue: orderTypeInitialValue,
          })(
            <Select
              style={{ width: 220 }}
              mode="multiple"
              maxTagCount={1}
              maxTagTextLength={5}
              onChange={(value: any) => {
                let menu: any[] = [];
                if (value.length === 1) {
                  const data = value[0];
                  if (data === '4') {
                    // 红利（包括加币-计入红利）
                    menu = ORDER_TYPE_DETAIL[3].children || [];
                  } else if (data === '13,14') {
                    // 加币（不计红利）
                    menu = ORDER_TYPE_DETAIL[5].children || [];
                  } else if (data === '10') {
                    // 减币
                    menu = ORDER_TYPE_DETAIL[9].children || [];
                  }
                  this.setState({ subMenu: menu });
                  return;
                }
                this.setState({ subMenu: [] });
              }}
            >
              {ORDER_TYPE_DETAIL.map((item: any) => (
                <Option value={item.value} key={item.value}>
                  {item.title}
                </Option>
              ))}
            </Select>,
          )}
        </FormItem>

        {/* 细分类型 */}
        <FormItem>
          {getFieldDecorator('subType', {
            initialValue: undefined,
          })(
            <Select
              style={{ width: '150px' }}
              maxTagCount={1}
              disabled={subMenu.length < 1}
              placeholder="请输入细分类型"
            >
              {subMenu.map((item: any) => (
                <Option value={item.value} key={item.value}>
                  {item.title}
                </Option>
              ))}
            </Select>,
          )}
        </FormItem>

        <FormItem>
          {/* 查询 */}
          <Button type="primary" htmlType="submit">
            查询
          </Button>
          {/* 重置 */}
          <Button style={{ marginLeft: '10px' }} onClick={this.handleReset}>
            重置
          </Button>
          {checkPermission(this.props.btns, this.exportPermission) ? (
            <Button style={{ marginLeft: '10px' }} onClick={this.handleExport}>
              导出
            </Button>
          ) : null}
        </FormItem>
      </Form>
    );
  };

  // 渲染表格
  private renderTable = (): ReactNode => {
    const { tableData, page, size, loading } = this.state;
    const { total } = this.state.tableData;

    return (
      <Table
        loading={loading}
        style={{ wordBreak: 'break-all', marginTop: '20px' }}
        columns={getTransationColumns(this.state.tableFilters, this.getColumnSearchProps)}
        dataSource={tableData.list}
        scroll={{ x: 2000, y: 540 }}
        rowKey={(record: any, index: number) => String(index)}
        onChange={this.onTableChange}
        pagination={{
          total,
          pageSize: size,
          current: page,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: () => `共 ${total} 条记录， 第${page}/${Math.ceil(total / size)}`,
          pageSizeOptions: PAGINATION_OPTION,
        }}
      />
    );
  };

  public render(): ReactNode {
    return (
      <div>
        {this.renderFilters()}
        {this.renderTable()}
      </div>
    );
  }
}

const TransactionWrapper = Form.create({ name: 'transactionReport' })(Transaction);

export default withRouter(
  connect(({ global }: { global: any }) => ({
    btns: global.btns,
  }))(TransactionWrapper),
);
